<div class="breadcrumbs breadcrumbs-fixed ace-save-state">
    <ul class="breadcrumb">
        <li>
            <i class="ace-icon fa fa-users home-icon"></i>
            <a href="#">优惠券管理</a>
        </li>
        <li class="active">优惠券列表</li>
    </ul>
</div>

<div class="page-content">
    <div class="row">
        <div class="col-xs-12">
            <h4 class="header smaller lighter blue">优惠券列表</h4>
            <div class="row">
                <div class="col-sm-2">
                    <a id="addManager" href="#manager-modal" data-toggle="modal"
                       class="btn btn-sm btn-success">
                        <i class="fa fa-plus"></i> 添加优惠券
                    </a>
                </div>
                <div class="col-sm-10">
                    <form id="searchForm" class="form-inline pull-right" role="search">

                        <div class="input-group ">
                            <label for="market">超市：</label>
                            <select name="market" id="market" style="width: 120px;height:34px">
                                <option value="">全部</option>
                            </select>
                        </div>
                        <div class="input-group ">
                            <label for="market">商家：</label>
                            <select name="store" id="store" style="width: 120px;height:34px">
                                <option value="">全部</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="type">优惠券类型：</label>
                            <select name="type" id="type" style="width: 120px;height:34px">
                                <option value="">全部</option>
                            </select>
                        </div>

                        <div class="checkbox">
                            <label>
                                <input type="checkbox" name="happyBag" value=""> 仅显示福袋优惠券
                            </label>
                        </div>

                        <button id="searchBtn" class="btn btn-xs btn-info" type="button">
                            <i class="ace-icon fa fa-search"></i> 搜索
                        </button>

                    </form>
                </div>
            </div>
            <div class="space-6"></div>
            <div class="dataTables_wrapper form-inline no-footer">
                <table id="company-table" class="table table-striped table-bordered table-hover">
                    <thead>
                    <tr>
                        <th class="center">序号</th>
                        <th>优惠券类型</th>
                        <th>优惠券名称</th>
                        <th>优惠方式</th>
                        <th>超市名称</th>
                        <th>商家名称</th>
                        <th>领取张数</th>
                        <th>使用张数</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                </table>
            </div>
        </div>
    </div>


    <div id="manager-modal" class="bootbox modal fade in" tabindex="-1" role="dialog" aria-hidden="false">
        <div class="modal-dialog" style="width: 50%">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" data-dismiss="modal" class="bootbox-close-button close close-button">×
                    </button>
                    <h5 class="modal-title">添加优惠券</h5>
                </div>
                <div class="modal-body">
                    <form id="manager-form" class="form-horizontal" role="form">
                        <div class="form-group">
                            <label class="col-sm-3 control-label no-padding-right" for="marketId"> 超市：</label>
                            <div class="col-sm-7">
                                <div class="clearfix"></div>
                                <select name="marketId"  id="marketId"  class="control-group col-xs-7" >

                                </select>
                            </div>
                        </div>



                        <div class="form-group ">
                            <label class="col-sm-3 control-label no-padding-right" for="storeId" >商家：</label>
                            <div class="col-sm-7">
                                <div class="clearfix"></div>
                                <select name="storeId"  id="storeId"  class="control-group col-xs-7" >

                                </select>
                            </div>

                        </div>
                        <div class="form-group ">
                            <label class="col-sm-3 control-label no-padding-right" for="typeId" >优惠券类型：</label>
                            <div class="col-sm-7">
                                <div class="clearfix"></div>
                                <select name="typeId"  id="typeId"  class="control-group col-xs-7" >

                                </select>
                            </div>


                        </div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label no-padding-right" for="ticketName">优惠券名称：</label>
                            <div class="col-sm-7">
                                <div class="clearfix"></div>
                                <input type="hidden" id="tid" name="id" >
                                <input type="text" id="ticketName" name="ticketName" class="col-xs-7">
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-sm-3 control-label no-padding-right" for="price">面值：</label>
                            <div class="col-sm-7">
                                <div class="clearfix"></div>
                                  <input type="text" id="price" name="price" class="col-xs-7" placeholder="折扣券请填1~10"><span style="line-height:40px">元/折</span>
                            </div>
                        </div>
                        <div class="form-group ">
                            <label class="col-sm-3 control-label no-padding-right" for="forever" >有效期：</label>
                            <div class="col-sm-7">
                                <div class="clearfix"></div>
                                <select name="forever"  id="forever"  class="control-group col-xs-7" >
                                    <option value="0" selected>期限</option>
                                    <option value="1">永久</option>
                                </select>
                            </div>

                        </div>

                        <div class="form-group">
                            <label  class="col-sm-3 control-label no-padding-right">生效时间</label>

                            <div class="col-sm-6">
                                <div class="clearfix"></div>
                                <div class="input-group date"  data-date-format="yyyy-MM-dd">
                                    <input type="text" class="form-control dateTimne"  name="startTime" >
                                    <div class="input-group-addon"><i class="fa fa-calendar bigger-110"></i></div>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label  class="col-sm-3 control-label no-padding-right">过期时间</label>
                            <div class="col-sm-6">
                                <div class="clearfix"></div>
                                <div class="input-group date"  data-date-format="yyyy-MM-dd">
                                    <input type="text" class="form-control dateTimne"  name="endTime" >
                                    <div class="input-group-addon"><i class="fa fa-calendar bigger-110"></i></div>
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-sm-3 control-label no-padding-right" for="priceDesc"> 使用条件：</label>
                            <div class="col-sm-6">
                                <div class="clearfix">
                                    <textarea name="priceDesc"  class="form-control" id="priceDesc" rows="3"></textarea>
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-sm-3 control-label no-padding-right" for="businessDesc"> 说明：</label>
                            <div class="col-sm-6">
                                <div class="clearfix">
                                    <textarea name="businessDesc"  class="form-control" id="businessDesc" rows="3"></textarea>
                                </div>
                            </div>
                        </div>

                        <!--<div class="form-group">-->
                            <!--<label class="col-sm-3 control-label no-padding-right"> 状态：</label>-->
                            <!--<div class="col-sm-9">-->
                                <!--<div class="clearfix">-->
                                    <!--<label>-->
                                        <!--<input id="status" name="status" class="ace ace-switch ace-switch-4 btn-flat"-->
                                               <!--type="checkbox" >-->
                                        <!--<span class="lbl"-->
                                              <!--data-lbl="启用 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 禁用"></span>-->
                                    <!--</label>-->
                                    <!--<input name="status" type="hidden">-->
                                <!--</div>-->
                                <!--&lt;!&ndash;<div class="switch" data-on-label="启用" data-off-label="禁用">&ndash;&gt;-->
                                    <!--&lt;!&ndash;<input id="status"  name="status" type="checkbox" checked />&ndash;&gt;-->
                                <!--&lt;!&ndash;</div>&ndash;&gt;-->
                            <!--</div>-->
                        <!--</div>-->
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" data-dismiss="modal" class="btn btn-sm btn-default close-button"><i
                            class="fa fa-undo close"></i> 取消
                    </button>
                    <button id="save-manager-btn" type="button" class="btn btn-sm btn-primary"><i
                            class="fa fa-check"></i> 保存
                    </button>
                </div>
            </div>
        </div>
    </div>


    <script type="text/javascript">
        var company_table;
        var marketList = [];
        var storeList = [];
        var ticketTypeList = [];
        $(function () {


            $(".dateTimne").datetimepicker({
                format:    'Y-M-D ',        // 设置时间年月日时分的格式 如: 2016/11/15 18:00
            });

            $.get(
                "ticket/getCompelexList",
                {},function(data){
                    marketList = data.marketList;
                    storeList = data.storeList;
                    ticketTypeList = data.ticketTypeList;

                    var options = "";
                    for(var i=0;i<marketList.length;i++){
                        options += "<option value='"+marketList[i].id+"'>"+marketList[i].name+"</option>";
                    }
                    $("#market option").after(options);

                    $("#marketId").append(options);

                    var optionsType = "";
                    for(var i=0;i<ticketTypeList.length;i++){
                        optionsType += "<option value='"+ticketTypeList[i].id+"'>"+ticketTypeList[i].name+"</option>";
                    }
                    $("#type option").after(optionsType);

                    $("#typeId").html(optionsType);
                }
            );


            $.get(
                "store/getStoreList",
                {},function(data){
                    storeList = data;
                }
            );

            $("#market").change(function(){
                var mid = $(this).val();
                $("#store").empty();
                var options = "<option value=''>全部</option>";
                for(var i=0;i<storeList.length;i++){
                    if(mid == storeList[i].marketId){
                        options += "<option value='"+storeList[i].id+"'>"+storeList[i].name+"</option>";
                    }
                }
                $("#store").html(options);
            });

            $("#marketId").change(function(){
                var mid = $(this).val();
                $("#storeId").empty();
                var options = "";
                for(var i=0;i<storeList.length;i++){
                    if(mid == storeList[i].marketId){
                        options += "<option value='"+storeList[i].id+"'>"+storeList[i].name+"</option>";
                    }
                }
                $("#storeId").html(options);
            });

            $("#forever").change(function(){
                if($(this).val() == 1){
                    $(".dateTimne").val("");
                    $(".dateTimne").attr("readOnly","readOnly");
                }else{
                    $(".dateTimne").removeAttr("readOnly");
                }

            });

            $("[name='happyBag']").click(function(){
                if($(this).prop("checked")){
                    $(this).val("1");
                }
            })


            var initParam =  $("#searchForm").serialize();
            company_table = $('#company-table').DataTable({
                language: {url: 'ace/json/dataTable_CN.json'},
                autoWidth: false,
                ordering: false,
                searching: false,
                serverSide: true,
                processing: true,
                deferRender: true,
                responsive: true,
                ajax: {
                    url: 'ticket/getAllList?'+initParam,
                },
                fnDrawCallback  : function(){
                            　　this.api().column(0, {
                                  search: 'applied',
                                  order: 'applied'
                              }).nodes().each(function(cell, i) {
                                  cell.innerHTML = i + 1;
                              });
                            },
                columns: [
                    {
                        data: null,
                        targets: 0
                    },
                    {
                        data: function (row) {

                            return row.ticketType.name;
                        }
                    },

                    {
                        data: 'ticketName',
                        defaultContent: ''
                    },
                    {
                        data: 'priceDesc',
                        defaultContent: ''
                    },
                    {
                        data: function (row) {

                            return row.store.market.name;
                        }
                    },
                    {
                        data: function (row) {

                            return row.store.name;
                        }
                    },
                    {
                        data: 'totalCount',
                        defaultContent: ''
                    }, {
                        data: 'isUseCount',
                        defaultContent: ''
                    }, {
                        data: 'createTime',
                        defaultContent: ''
                    },
                    {
                        data: function (row) {
                            var edit = '&nbsp;&nbsp;<a  href="javascript:;" data-id="' + row.id + '" class="btn btn-xs btn-primary edit"><i class="fa fa-pencil"></i> 编辑</a>';
                            var del = '&nbsp;&nbsp;<a  href="javascript:;" data-id="' + row.id + '" class="btn btn-xs btn-danger delete"><i class="fa fa-trash"></i> 删除</a>';
                            var bag = '&nbsp;&nbsp;<a  href="javascript:;" data-id="' + row.id + '" class="btn btn-xs btn-info modifyBag"><i class="fa fa-plus"></i>'+(row.isHappyBag?"移出福袋":"加入福袋") +'</a>';
                            return edit+del+bag;
                        }
                    }
                ]
            });



            $('#searchBtn').click(function () {
                var param = $("#searchForm").serialize();

                company_table.ajax.url("ticket/getAllList?" + param).load();
            });


            $("#company-table tbody").on("click", ".edit", function () {
                var id = $(this).data("id");
                $.get("ticket/editTicket/" + id, function (data) {
                   $("#ticketName").val(data.ticketName);
                   $("#price").val(data.price);
                   $("#priceDesc").val(data.priceDesc);
                   $("#businessDesc").val(data.businessDesc);
                   $("[name='startTime']").val(data.startTime);
                   $("[name='endTime']").val(data.endTime);
                   $("#tid").val(data.id);

                   $("#marketId option").each(function(){
                      if(data.store.market.id == $(this).val()){
                          $(this).prop("selected",true);
                          var options = "";
                          for(var i=0;i<storeList.length;i++){
                              if(data.store.market.id == storeList[i].marketId){
                                  var sel = data.storeId == storeList[i].id?"selected":"";
                                  options += "<option value='"+storeList[i].id+"' "+sel+" >"+storeList[i].name+"</option>";
                              }
                          }
                          $("#storeId").html(options);
                      }
                   });

                   $("#typeId option").each(function(){
                      if(data.typeId == $(this).val()){
                          $(this).prop("selected",true);
                      }
                   });

                   $("#forever option").each(function(){
                      if(data.isForever && $(this).val() == 1){
                          $(".dateTimne").attr("readOnly",true);
                          $(this).prop("selected",true);
                      }else if(!data.isForever && $(this).val() == 0){
                          $(this).prop("selected",true);
                      }
                   });

                   $("#manager-modal").modal('show');
                });
            });

            //删除
            $("#company-table tbody").on("click", ".delete", function () {
                var id = $(this).data("id");
                bootbox.confirm("确定要删除这个优惠券？", function (f) {
                    if (f) {
                        $.post("ticket/removeTicket/" + id, function (data) {
                            company_table.ajax.reload();
                        });
                    }})
            });

            //加入或移出福袋
            $("#company-table tbody").on("click", ".modifyBag", function () {
                $.post("ticket/modifyBag/"+$(this).data("id"),{},function(){
                    bootbox.alert("加入或移出福袋成功！");
                    company_table.ajax.reload();
                });
            });


            //初始化表单校验
            var video_validator = $("#manager-form").validate({
                errorElement: 'div',
                errorClass: 'help-block',
                focusInvalid: false,
                ignore: "",
                rules: {
                    ticketName: {
                        required: true
                    },
                    price: {
                        required: true,
                        number:true
                    },
                    storeId: {
                        required: true
                    },

                },
                messages: {
                    ticketName: {
                        required: "优惠券名称不能为空"
                    },
                    price: {
                        required: "面值不能为空",
                        number:"请填写数字"
                    },
                    storeId: {
                        required: "商家不能为空"
                    },

                }, highlight: function (e) {
                    $(e).closest('.form-group').removeClass('has-info').addClass('has-error');
                }, success: function (e) {
                    $(e).closest('.form-group').removeClass('has-error');
                    $(e).remove();
                }, errorPlacement: function (error, element) {
                    if (element.is('input[type=checkbox]') || element.is('input[type=radio]')) {
                        var controls = element.closest('div[class*="col-"]');
                        if (controls.find(':checkbox,:radio').length > 1) controls.append(error);
                        else error.insertAfter(element.nextAll('.lbl:eq(0)').eq(0));
                    } else if (element.is('.select2')) {
                        error.insertAfter(element.siblings('[class*="select2-container"]:eq(0)'));
                    }
                    else if (element.is('.chosen-select')) {
                        error.insertAfter(element.siblings('[class*="chosen-container"]:eq(0)'));
                    }
                    else {
                        error.insertAfter(element.parent());
                    }
                }
            });


            $("#save-manager-btn").click(function () {
                if ($("#manager-form").valid()){

                    $("#manager-form").ajaxSubmit({
                        url: 'ticket/saveTicket',
                        type: 'post',
                        success: function (data) {
                            $("#manager-modal").modal('hide');
                            $("#manager-modal input").val("");
                            company_table.ajax.reload();
                        }
                    });
                }

            });

            //模态框隐藏事件
            $("#manager-modal").on("hide.bs.modal", function () {
                $("#manager-form")[0].reset();
                $("#storeId").empty();
                $(".dateTimne").attr("readOnly",false);
                video_validator.resetForm();
                $("#manager-form .form-group").removeClass("has-error");
            });

            $(".close-button").click(function(){
                $("#manager-modal input").val("");
                $("#statusName").prop("checked",false);
            })

        });
    </script>
</div>